package com.heima.user.service.Impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.heima.common.exception.CustException;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.dtos.LoginDTO;
import com.heima.model.user.pojos.ApUser;
import com.heima.user.mapper.ApUserMapper;
import com.heima.user.service.ApUserLoginService;
import com.heima.utils.common.AppJwtUtil;
import io.seata.common.util.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.HashMap;
import java.util.Map;

@Service
public class ApUserLoginServiceImpl implements ApUserLoginService {
    @Autowired
    ApUserMapper apUserMapper;

    @Override
    public ResponseResult login(LoginDTO dto) {
        //1。校验参数
        if (dto.getEquipmentId() == null) {
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID);//501无效参数
        }
        //2。使用手机号+密码方式登录
        if (StringUtils.isNotBlank(dto.getPhone()) && StringUtils.isNotBlank(dto.getPassword())) {
            //2.1使用手机号查询用户状态
            ApUser apUser = apUserMapper.selectOne(Wrappers.<ApUser>lambdaQuery().eq(ApUser::getStatus, 0)
                    .eq(ApUser::getPhone, dto.getPhone()));

            if (apUser == null) {
                CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST, "请检查手机号");
            }
            //2.2确认密码和数据库的密码一致
            String apUserPwd = apUser.getPassword();
            String newPwd = DigestUtils.md5DigestAsHex((dto.getPassword() + apUser.getSalt()).getBytes());
            if (!newPwd.equals(apUserPwd)) {
                CustException.cust(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR, "密码错误");
            }
            //2.3一致 密码颁发token  返回结果user  token
            String token = AppJwtUtil.getToken(Long.valueOf(apUser.getId()));

            Map result = new HashMap<>();
            apUser.setPassword("");
            apUser.setSalt("");
            result.put("user", apUser);
            result.put("token", token);
            return ResponseResult.okResult(result);

        }else {
            if (dto.getEquipmentId()==null){
                CustException.cust(AppHttpCodeEnum.PARAM_INVALID,"手机设备id不能为空");//501无效参数
            }

        //3.如果手机号或者密码为空，那么使用设备id登录
            String token = AppJwtUtil.getToken(0L);

            //3.1直接发token存储用户id  0
            Map result = new HashMap<>();
            result.put("token", token);
            return ResponseResult.okResult(result);

        }
    }
}
